package com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.springframework.web.multipart.MultipartFile;

public class FileUtils {
	public static void createFile(String path) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static String getFileType(String filename) {
		return filename.substring(filename.lastIndexOf(".") + 1);
	}

	public static String getRelativePath(String urlpath) {
		String path = urlpath.substring(urlpath.indexOf("/ysjapp/") + 8);
		return path.replace("/", "\\");
	}

	public static void upload(String urlString, String filename) throws Exception {
		URL url = new URL(urlString);
		URLConnection con = url.openConnection();
		InputStream is = con.getInputStream();
		byte[] bs = new byte[1024];

		OutputStream os = new FileOutputStream(filename);
		int len;
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		os.close();
		is.close();
	}

	public static void uploadfile(MultipartFile img, String filepath) throws IllegalStateException, IOException {
		File file = new File(filepath);
		img.transferTo(file);
	}

	public static void main(String[] args) throws Exception {
		upload("http://q.qlogo.cn/qqapp/1105839114/9684A81950DB17BAC2E83BA039A801EB/100",
				"D:\\apache-tomcat-7.0.64\\wtpwebapps\\ysjapp\\serverimg\\headimg\\2.jpg");
	}
}
